﻿//https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/?envType=study-plan-v2&envId=top-100-liked

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root)
    {
        TreeNode* cur = root;
        while (cur)
        {
            //如果左子树不为空
            if (cur->left)
            {
                //保存当前节点的左子树
                TreeNode* left = cur->left;
                //定义当前节点的前驱结点--一定在左子树中
                TreeNode* prev = left;
                while (prev->right)
                {
                    //找到左子树的最右节点作为前驱节点
                    prev = prev->right;
                }
                //当前节点的右子树作为前驱结点的右子树
                prev->right = cur->right;
                //当前节点的左子树移到右子树
                cur->right = left;
                //左子树置空
                cur->left = nullptr;
            }
            //移到下一个节点
            cur = cur->right;
        }
    }
};